﻿using Microsoft.Extensions.Hosting;
using MQTTnet;
using System.Text;

namespace Leo.Common.MQTT
{
    public class MQTTConsumer : BackgroundService
    {
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            await CreateConnectionAsync();
            Console.WriteLine("ccccc");
        }

        public async Task<string> CreateConnectionAsync()
        {
            //创建MQTT客户端工厂，用于创建MQTT客户端实例
            var mqttFactory = new MqttClientFactory();

            //通过工厂创建MQTT客户端
            var mqttClient = mqttFactory.CreateMqttClient();

            // 使用建造者模式创建MQTT客户端连接选项
            var option = new MqttClientOptionsBuilder()
                 .WithTcpServer("localhost", 1883)  //设置MQTT 服务器 地址和端口
                 .WithProtocolVersion(MQTTnet.Formatter.MqttProtocolVersion.V311)
                 .WithCleanSession()   // 设置 清洁会话（不保留历史会话状态）
                 .WithClientId("testClient")   // 设置客户端唯一标识
                 .Build();   //  构建配置选项对象

            // 使用 配置的选项 连接 MQTT服务器
            var result = await mqttClient.ConnectAsync(option);

            // 检查客户端 是否连接成功
            if (mqttClient.IsConnected)
            {
                await Console.Out.WriteLineAsync("MQTT 客户端连接成功");
            }
            else
            {
                await Console.Out.WriteLineAsync("MQTT 客户端连接失败");
            }

            mqttClient.ApplicationMessageReceivedAsync += MqttClient_ApplicationMessageReceivedAsync;

            var mqttSubscribeOptions = mqttFactory.CreateSubscribeOptionsBuilder().WithTopicFilter("test").Build();
            await mqttClient.SubscribeAsync(mqttSubscribeOptions, CancellationToken.None);

            Console.WriteLine("MQTT client subscribed to topic.");

            return "OK";
        }
        private Task MqttClient_ApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs arg)
        {
            var ss = arg.ApplicationMessage.Payload.Slice(0, arg.ApplicationMessage.Payload.Length);
            string str = System.Text.Encoding.UTF8.GetString(ss);

            Console.WriteLine(str);
            return Task.CompletedTask;
        }
    }
}
